package com.zyylr.classroomreservationsystem.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.widget.PullRefreshLayout;
import com.example.lance.clockview.ClockView;
import com.kunzisoft.switchdatetime.SwitchDateTimeDialogFragment;
import com.zyylr.classroomreservationsystem.R;
import com.zyylr.classroomreservationsystem.activity.ShowFreeClassroomActivity;
import com.zyylr.classroomreservationsystem.bean.Building;
import com.zyylr.classroomreservationsystem.bean.Msg;
import com.zyylr.classroomreservationsystem.web.IClassroom;
import com.zyylr.classroomreservationsystem.web.RetrofitFactory;


import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * 根据时间查询空闲教室的界面
 */
public class TimeToClassroomFragment extends DialogFragment {
    private static final String TAG_DATETIME_FRAGMENT = "TAG_DATETIME_FRAGMENT";
    private static final String STATE_TEXTVIEW = "STATE_TEXTVIEW";
    private static final String TAG = "time2classroom";
    final SimpleDateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", java.util.Locale.getDefault());

    private TextView textViewStart, textViewEnd;
    private Button btnSubmit;
    private SwitchDateTimeDialogFragment dateTimeFragment;
    private ClockView clockViewStart, clockViewEnd;
    private PullRefreshLayout pullRefreshLayout;

    private long startTime = -1L, endTime = -1L;    //选择的起始时间和结束时间时间戳

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_time_to_classroom, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        textViewStart = getActivity().findViewById(R.id.textView_start_time);
        textViewEnd = getActivity().findViewById(R.id.textView_end_time);
        clockViewStart = getActivity().findViewById(R.id.cv_start_time);
        clockViewEnd = getActivity().findViewById(R.id.cv_end_time);
        btnSubmit = getActivity().findViewById(R.id.button_submit);

        initClockView(clockViewStart);
        initClockView(clockViewEnd);
        initDialog();

        setChooseTimeClockViewListener(clockViewStart, 1);
        setChooseTimeClockViewListener(clockViewEnd, 2);
        setSubmitBtnListener();
    }

    /**
     * 初始化时钟，设置未当前时间并让其走动
     */
    private void initClockView(ClockView clockView) {
        Calendar rightNow = Calendar.getInstance();
        setClockViewTime(clockView, rightNow);
        clockView.start();
    }

    /**
     * 初始化选择时间的对话框选项
     */
    private void initDialog() {
        dateTimeFragment = (SwitchDateTimeDialogFragment) getChildFragmentManager().findFragmentByTag(TAG_DATETIME_FRAGMENT);
        if (dateTimeFragment == null) {
            dateTimeFragment = SwitchDateTimeDialogFragment.newInstance(
                    getString(R.string.label_datetime_dialog),
                    getString(android.R.string.ok),
                    getString(android.R.string.cancel),
                    getString(R.string.clean) // Optional
            );
        }
        dateTimeFragment.setTimeZone(TimeZone.getDefault());
        final SimpleDateFormat myDateFormat = new SimpleDateFormat("yyyy MM dd HH:mm", java.util.Locale.getDefault());
        dateTimeFragment.set24HoursMode(true);
        dateTimeFragment.setHighlightAMPMSelection(false);
        try {
            dateTimeFragment.setSimpleDateMonthAndDayFormat(new SimpleDateFormat("MMMM dd", Locale.getDefault()));
        } catch (SwitchDateTimeDialogFragment.SimpleDateMonthAndDayFormatException e) {
            Log.e(TAG, e.getMessage());
        }
    }

    /**
     * 选择时间的clockView监听器，点击后出现时间选择控件
     *
     * @param clockView 哪个时钟被点击
     * @param which     对应哪个时间, 1：开始时间；2：结束时间
     */
    private void setChooseTimeClockViewListener(final ClockView clockView, final int which) {

        clockView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //没选择预约起始时间就选择结束时间
                if (which == 2 && textViewStart.getText().toString().equals("")) {
                    Toast.makeText(getContext(), "请先选择预约起始时间", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (which == 1) {
                    Calendar rightNow = Calendar.getInstance();
                    //设置不让其选择之前的时间
                    dateTimeFragment.setMinimumDateTime(rightNow.getTime());
                    //最多只能预约一周内的教室
                    dateTimeFragment.setMaximumDateTime(new Date(rightNow.getTimeInMillis() + 7 * 24 * 60 * 60 * 1000));
                    // 从时间选择页面开始
                    dateTimeFragment.startAtTimeView();
                    //设置日期选择器初始时间为当前时间
                    dateTimeFragment.setDefaultDateTime(rightNow.getTime());
                } else if (which == 2) {
                    //走到这步说明已选择预约开始时间，将用于选择预约结束的时间选择器初始时间设为预约开始时间
                    Calendar startTimeCalendar = Calendar.getInstance();
                    startTimeCalendar.setTime(new Date(startTime));
                    //设置不让其选择比开始时间早的时间，且预约时间段不能小于30分钟
                    Date minimumTime = new Date(startTime + 30 * 60 * 1000);
                    //此控件设置最小时间只能精确到日期
                    dateTimeFragment.setMinimumDateTime(minimumTime);
                    dateTimeFragment.setDefaultDateTime(minimumTime);
                    //不能预约第二天的教室
                    Calendar nextDay = startTimeCalendar;
                    nextDay.set(Calendar.HOUR_OF_DAY, 23);
                    nextDay.set(Calendar.MINUTE, 59);
                    nextDay.set(Calendar.SECOND, 0);
                    dateTimeFragment.setMaximumDateTime(nextDay.getTime());
                }
                setDialogListener(which);
                dateTimeFragment.show(getChildFragmentManager(), TAG_DATETIME_FRAGMENT);
            }
        });
    }

    /**
     * 给时间选择对话框设置监听器
     *
     * @param which 哪个按钮触发的对话框
     */
    private void setDialogListener(final int which) {
        dateTimeFragment.setOnButtonClickListener(new SwitchDateTimeDialogFragment.OnButtonWithNeutralClickListener() {
            //确定按钮
            @Override
            public void onPositiveButtonClick(Date date) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                switch (which) {
                    case 1:
                        setClockViewTime(clockViewStart, calendar);
                        clockViewStart.stop();
                        textViewStart.setText(myDateFormat.format(date));
                        startTime = date.getTime();
                        Log.d(TAG, "onPositiveButtonClick: start_time date=" + date + " timestamp= " + startTime);
                        break;
                    case 2:
                        setClockViewTime(clockViewEnd, calendar);
                        clockViewEnd.stop();
                        textViewEnd.setText(myDateFormat.format(date));
                        endTime = date.getTime();
                        Log.d(TAG, "onPositiveButtonClick: end_time date=" + date + " timestamp= " + endTime);
                        break;
                }
            }

            //取消按钮
            @Override
            public void onNegativeButtonClick(Date date) {
                // Do nothing
            }

            //清除按钮
            @Override
            public void onNeutralButtonClick(Date date) {
                if (which == 1) {
                    startTime = -1L;
                    textViewStart.setText("");
                    initClockView(clockViewStart);
                } else if (which == 2) {
                    endTime = -1L;
                    textViewEnd.setText("");
                    initClockView(clockViewEnd);
                }
            }
        });
    }

    /**
     * 通过calendar给clockView设置时间
     *
     * @param clockView
     * @param calendar
     */
    private void setClockViewTime(ClockView clockView, Calendar calendar) {
        clockView.setTime(
                calendar.get((Calendar.HOUR_OF_DAY)),
                calendar.get((Calendar.MINUTE)),
                calendar.get((Calendar.SECOND))
        );
    }

    private void setSubmitBtnListener() {
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (startTime == -1 || endTime == -1) {
                    Toast.makeText(getContext(), "请选择时间段！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (endTime <= startTime) {
                    Toast.makeText(getContext(), "开始时间不能迟于或等于结束时间！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (endTime - startTime < 30 * 60 * 1000) {
                    Toast.makeText(getContext(), "预约时间不能小于半小时！", Toast.LENGTH_SHORT).show();
                    return;
                }
                Retrofit retrofit = RetrofitFactory.getRetrofit();
                IClassroom request = retrofit.create(IClassroom.class);
                Call<Msg<List<Building>>> call = request.getFreeClassroomCall("" + startTime, "" + endTime);
                call.enqueue(new Callback<Msg<List<Building>>>() {
                    @Override
                    public void onResponse(Call<Msg<List<Building>>> call, Response<Msg<List<Building>>> response) {
                        Msg msg = response.body();
                        Log.d(TAG, "msg= " + msg);
                        try {
                            assert msg != null;
                            //登录错误，toast错误信息
                            if (msg.getCode() == 200) {
                                Toast.makeText(getContext(), msg.getMsg(), Toast.LENGTH_SHORT).show();
                                return;
                            }
                            List<Building> buildings = (List<Building>) msg.getExtend().get("buildings");
                            Intent intent = new Intent(getActivity(), ShowFreeClassroomActivity.class);
                            intent.putExtra("buildings", (Serializable) buildings);
                            intent.putExtra("start_time", startTime);
                            intent.putExtra("end_time", endTime);
                            startActivity(intent);
                        } catch (Exception e) {
                            Toast.makeText(getContext(), "数据解析错误！", Toast.LENGTH_SHORT).show();
                            Log.e(TAG, e.getMessage());
                        }

                    }

                    @Override
                    public void onFailure(Call<Msg<List<Building>>> call, Throwable t) {
                        Toast.makeText(getContext(), "服务请求错误！", Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });
    }

}